import re

from django.contrib.auth import authenticate, login, logout
from django.core.paginator import Paginator
from apps.goods.models import Youhuiquan
from apps.order.models import OrderInfo, OrderGoods
from utils.mixin import LoginRequiredMixin
from apps.user.models import User, Address
from django.shortcuts import render, redirect
from django.views import View
from django_redis import get_redis_connection
from apps.goods.models import Goods


class UserInfoView(LoginRequiredMixin, View):
    """ 用户中心——信息页"""

    def get(self, request):
        redis_conn = get_redis_connection("default")
        user_id = request.user.id
        quan = Youhuiquan.objects.filter(owner=user_id).values('name')

        if not quan:
            yhq = None
        else:
            for item in quan:
                yhq = item['name']
        data = {
            "page": "info",
            "quan": yhq
        }
        history_list = redis_conn.lrange('history_%d' % user_id, 0, 4)  # 获取前5个历史浏览记录
        history_data = Goods.objects.filter(id__in=history_list)
        data.update(history_data=history_data)
        return render(request, 'user_center_info.html', data)


class UserOrderView(LoginRequiredMixin, View):
    """ 用户中心——订单页"""

    def get(self, request, page):
        # 获取用户订单信息
        user_id = request.user.id

        order_list = OrderInfo.objects.filter(user_id=user_id).order_by('-create_time')
        for order_item in order_list:
            order_goods = OrderGoods.objects.filter(order_info=order_item)
            order_item.order_goods = order_goods
            order_item.status_name = OrderInfo.ORDER_STATUS[order_item.status]

        order_page = Paginator(order_list, 3)  # 3条数据为一个页码
        try:
            page = int(page)
        except Exception as e:
            page = 1

        if page > order_page.num_pages:
            page = 1

        order_list = order_page.page(page)

        if order_page.num_pages < 5:
            page_range = range(1, order_page.num_pages + 1)
        elif order_list.number <= 3:
            page_range = range(1, 6)
        elif order_page.num_pages - order_list.number <= 3:
            page_range = range(order_page.num_pages - 4, order_page.num_pages + 1)
        else:
            page_range = range(order_list.number - 2, order_list.number + 3)

        data = {
            "page": "order",
            "orders": order_list,
            "page_range": page_range
        }
        return render(request, 'user_center_order.html', data)


class AddressView(LoginRequiredMixin, View):
    """ 用户中心——地址页"""

    def get(self, request):
        data = {
            "page": "address"
        }
        # 获取用户默认收货地址
        data = Address.objects.filter(user_id=request.user.id)
        # if addr:
        #     data['addr_str'] = "%s （%s 收） %s" % (addr.addr, addr.receiver, addr.phone)
        return render(request, 'user_center_site.html', {'data':data})

    def post(self, request):
        data = {
            "page": "address"
        }
        user = request.user
        receiver = request.POST.get('receiver')
        addr = request.POST.get('addr')
        phone = request.POST.get('phone')

        if not all([receiver, addr, phone]):
            error = "收件人、详细地址、手机号不能为空"
            return render(request, 'user_center_site.html', {"error": error})
        if not re.match(r'^1[0-9]{10}$', phone):
            error = "手机号填写错误"
            return render(request, 'user_center_site.html', {"error": error})

        # 如果改用户当前没有默认地址，则新添加的地址为默认地址
        default_addr = Address.objects.getDefaultAddress(user)
        if default_addr:
            is_default = False
        else:
            is_default = True

        Address.objects.create(user=user, receiver=receiver, addr=addr, phone=phone,
                               is_default=is_default)

        return redirect('/user/address/')


class LoginView(View):
    def get(self, request):
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = 'checked'
        else:
            username = ''
            checked = ''
        return render(request, 'login.html', {
            'username': username,
            'checked': checked
        })

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')

        if not all([username, password]):
            return render(request, 'login.html', {'errmsg': "请填写完整"})

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            response = redirect('/')
            remember = request.POST.get('remember')
            if remember == 'on':
                response.set_cookie('username', username, max_age=7 * 24 * 60 * 60)
            else:
                response.delete_cookie('username')

            return response

        else:
            return render(request, 'login.html', {'errmsg': '用户名或密码错误'})


class LogoutView(View):
    def get(self, request):
        logout(request)
        return redirect('/user/login/')


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        """ 注册处理 """
        username = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        email = request.POST.get('email')

        if not all([username, pwd, email]):
            return render(request, 'register.html', {'errmsg': '请填写完整'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'register.html', {'errmsg': '邮箱格式不正确'})
        # 校验用户名是否重复
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = None
        if user:
            return render(request, 'register.html', {'errmsg': '用户名已存在'})
        # 用户注册
        user = User.objects.create_user(username, email, pwd)
        user.is_active = 1
        user.save()
        # 返回应答，跳转到登录页
        return redirect('/user/login/')
